<?php

namespace app\api\model\appointment;

use app\common\model\BaseModel;


/**
 * 预约时间模型
 * Class PointsLog
 * @package app\store\model\user
 */
class Time extends BaseModel
{
    protected $name = 'appointment_time';

    /**
     *  预约时间
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getList($param = [])
    {
        // 获取列表数据
        return $this->where('is_delete', 0)
            ->where('status', 1)
            ->where($param)
            ->order('sort asc')
            ->field('time_id,name')->select();
    }

    /*
    * 获取可预约的时间段列表
    */

    public static function useTimeList($type_id,$date){

        $where = [
            'wxapp_id' => self::$wxapp_id,
            'is_delete' => 0,
            'type_id' => $type_id,
        ];

        $count = Db("appointment_type")
            ->where($where)
            ->value('count');
        $list = Self::where($where)
            ->where('status', 1)
            ->field('time_id,name,desc')
            ->order("sort asc")
            ->select()->toArray();

        $cur_date = strtotime(date("Y-m-d", time()));
        $lower_state = $cur_date - $date == 0 ? 1 : 0;
        foreach ($list as $k => $v) {
            $use_count = Db("appointment_order")
                ->where("appointment_date", $date)
                ->where("time_id", $v['time_id'])
                ->where("status", 'in', [1, 2])
                ->where($where)
                ->count();

            $state = false;
            $arr = explode('~', $v['desc']);
            if ($lower_state && count($arr) == 2) {
                $m1 = getMinute(date("H:m", time()));
                $m2 = getMinute($arr[1]);
                if ($m1 >= $m2) {
                    $list[$k]['use_count'] = 0;
                    $state = true;
                    unset($list[$k]);
                }
            }

            if (!$state) {
                $config_count = Db("appointment_config")
                    ->where("type_id", $type_id)
                    ->where("date", $date)
                    ->where("time_id", $v['time_id'])
                    ->where($where)->find();
                $all_count = isset($config_count['count']) ? $config_count['count'] : $count;
                if(($all_count - $use_count) == 0){
                    unset($list[$k]);
                }
            }
        }
        $list = array_values($list);
        return $list;
    }

}